/**
Copyright (c) 2011  Nicholas Zhu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.cardgroup.cbrp.springmem.aop;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.rubyeye.xmemcached.GetsResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.cardgroup.cbrp.springmem.annotations.ReadSingleCache;
import com.cardgroup.cbrp.springmem.config.ExpirationTime;
import com.cardgroup.cbrp.springmem.data.CacheData;
import com.cardgroup.cbrp.springmem.util.DateUtil;

/**
 * ReadSingleCacheAdvice
 * Get two keys:
 * 1. Group Key: checking the latest update time
 * 2. Cache Key: getting data which is a instance of CacheData
 * @author nicholas
 * @see CacheData SingleCacheAnnotationDataBuilder
 */
@Aspect
public class ReadSingleCacheAdvice extends AdviceBase {
	private static final Log LOG = LogFactory.getLog(ReadSingleCacheAdvice.class);
	
	@Pointcut("@annotation(com.cardgroup.cbrp.springmem.annotations.ReadSingleCache)")
	public void getSingle() {
	}
	
	@Around("getSingle()")
	public Object cacheGetSingle(ProceedingJoinPoint pjp) throws Throwable {
		SingleCacheAnnotationDataBuilder builder = new SingleCacheAnnotationDataBuilder(ReadSingleCache.class, pjp);
		AnnotationDataDesigner designer = new AnnotationDataDesigner(builder);
		final AnnotationData annotationData = designer.generateAnnotation();
		Date updateDate = null;
		try {
			// get multi-keys
			List<String> keys = new ArrayList<String>(0);
			keys.add(annotationData.getGroupKey());
			keys.add(annotationData.getKey());
			// get multi-data
			Map<String, GetsResponse<Object>> result = cache.gets(keys);
			GetsResponse timestamp = result.get(annotationData.getGroupKey());
			if(timestamp != null){
				updateDate = (Date)timestamp.getValue();
				// data
				GetsResponse data = result.get(annotationData.getKey());
				if(data != null){
					if(DateUtil.compareDate(updateDate, ((CacheData)data.getValue()).getDate()) < 0){
						LOG.debug("cache hit");
						return ((CacheData)data.getValue()).getObject();
					}
					
				}
			}
		}catch (Throwable ex) {
			LOG.warn("Caching on " + pjp.toShortString()
					+ " aborted due to an error.", ex);
			return pjp.proceed();
		}
		final Object result = pjp.proceed();
		try {
			final Object submission = (result == null) ? new PertinentNegativeNull()
					: result;
			// Cache group key
			CacheData data = new CacheData();
			if(updateDate == null){
				updateDate = new Date();
				// By default, the expiration time of update cache is 1 day.
				cache.set(annotationData.getGroupKey(), ExpirationTime.DAY, updateDate);
			}
			data.setDate(new Date());
			data.setObject(submission);
			// Cache data
			cache.set(annotationData.getKey(), annotationData.getExpiration(), data);
		} catch (Throwable ex) {
			LOG.warn("Caching on " + pjp.toShortString()
					+ " aborted due to an error.", ex);
		}
		return result;
	}
}
